package com.dd.cloud.user.service.mechan.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.AdminConstants;
import com.dd.cloud.common.constants.HealthConstants;
import com.dd.cloud.common.constants.MechanConstants;
import com.dd.cloud.common.constants.UserConstants;
import com.dd.cloud.user.entity.admin.AdminSaleInfo;
import com.dd.cloud.user.entity.admin.SaleInviteMechan;
import com.dd.cloud.user.entity.agent.Agent;
import com.dd.cloud.user.entity.agent.AgentMechanBind;
import com.dd.cloud.user.entity.doctor.DoctorDetail;
import com.dd.cloud.user.entity.doctor.DoctorUser;
import com.dd.cloud.user.entity.mechan.*;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.user.mapper.mechan.MechanRankMapper;
import com.dd.cloud.user.req.mechan.*;
import com.dd.cloud.user.res.mechan.*;
import com.dd.cloud.user.service.admin.IAdminSaleInfoService;
import com.dd.cloud.user.service.admin.ISaleInviteMechanService;
import com.dd.cloud.user.service.agent.IAgentMechanBindService;
import com.dd.cloud.user.service.agent.IAgentService;
import com.dd.cloud.user.service.aicms.IAicmsDepartmentService;
import com.dd.cloud.user.service.aicms.IAicmsDiseaseService;
import com.dd.cloud.user.service.doctor.IDoctorUserService;
import com.dd.cloud.user.service.mechan.*;
import com.dd.cloud.user.service.phar.IPharmacyChooseService;
import com.dd.cloud.user.service.role.IAdminPowerService;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.enums.ZkResponseEnum;
import com.dd.cloud.common.exception.ZekeAuthException;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 机构层级表 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-04-27
 */
@Service
@Slf4j
public class MechanRankServiceImpl extends ServiceImpl<MechanRankMapper, MechanRank> implements IMechanRankService {

    @Autowired
    private IMechanUserService mechanUserService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IDoctorUserService doctorUserService;
    @Autowired
    private IMechanReviewLogService mechanReviewLogService;
    @Autowired
    private IMechanRankApplyService mechanRankApplyService;
    @Autowired
    private ISaleInviteMechanService saleInviteMechanService;
    @Autowired
    private IAdminSaleInfoService adminSaleInfoService;
    @Autowired
    private IAgentService agentService;
    @Autowired
    private IAgentMechanBindService agentMechanBindService;


    /**
     * 获取机构信息
     *
     * @param mechanId
     * @return
     */
    @Override
    public MechanRankDetailRes getMechanRankInfo(Integer mechanId) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        if (mechanId == null) {
            mechanId = loginInfo.getMechanId();
        }
        return getBaseMapper().getMechanDetail(mechanId);
    }

    /**
     * 添加机构
     *
     * @param req
     */
    @Override
    @Transactional
    public MechanRank addMechanRank(MechanRankAddReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        if (loginInfo.getType() != LoginInfo.UserType.ADMIN) {
            throw new ZekeException(ZkExceptionEnum.NO_ERMSSION);
        }
//        if (loginInfo.getType() == LoginInfo.UserType.ADMIN && req.getTapId() == null) {
//            req.setTapId(1);
//        }
        QueryWrapper<MechanRank> qw = new QueryWrapper<>();
        qw.lambda().eq(MechanRank::getName, req.getName())
                .ne(MechanRank::getStatus, MechanConstants.MechanStatus.DEL);
        MechanRank mechanRank = getOne(qw);
        if (mechanRank != null) {
            throw new ZekeException(400, "机构名字已存在");
        }
        if (mechanUserService.checkPhoneUsed(req.getAdminPhone())) {
            throw new ZekeException(400, "手机号已使用");
        }
        mechanRank = new MechanRank();
        BeanUtils.copyProperties(req, mechanRank);
        mechanRank.setStatus(MechanConstants.MechanStatus.NORMAL);

        mechanRank.setCreateId(loginInfo.getId());
        mechanRank.setCreateType(loginInfo.getType());
        mechanRank.setCreateName(loginInfo.getName());
        mechanRank.setGlobalId(UUID.randomUUID().toString());
        int i = getBaseMapper().insert(mechanRank);
        if (i <= 0) {
            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
        }
        int id = mechanRank.getId();
        //添加管理员
        MechanUser mechanUser = new MechanUser();
        mechanUser.setAccount(req.getAdminPhone());
        mechanUser.setPhone(req.getAdminPhone());
        mechanUser.setName(req.getAdminName());
        mechanUser.setCreateName(loginInfo.getName());
        mechanUser.setCreateDate(LocalDateTime.now());
        String salt = CodecUtils.generateSalt();
        mechanUser.setSalt(salt);
        mechanUser.setPassword(CodecUtils.md5Hex(mechanUser.getPhone().substring(mechanUser.getPhone().length() - 6), mechanUser.getSalt()));
        mechanUser.setMechanId(id);
        mechanUser.setType(MechanConstants.MechanUserType.ADMIN);
        mechanUser.setStatus(MechanConstants.MechanUserStatus.NORMAL);
        mechanUser.setCreateId(loginInfo.getId());
        boolean flag = mechanUserService.save(mechanUser);
        if (!flag) {
            throw new ZekeException(400, "添加机构管理员失败");
        }
//        req.getDepList().forEach(dep -> {
//            dep.setUserId(id);
//            dep.setUserType(LoginInfo.UserType.MECHAN);
//        });
//        //设置机构科室疾病
//        mechanDepartmentService.setMechanDepartment(req.getDepList());
//        pharmacyChooseService.saveOrUpdatePharChooseByMechanId(2, mechanRank.getId(), null);
        return mechanRank;
    }

    /**
     * excel批量添加机构
     *
     * @param file
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addMechanRankByExcel(MultipartFile file) {
        Integer tapId = 1;
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        if (loginInfo.getType() != LoginInfo.UserType.ADMIN) {
            throw new ZekeException(ZkExceptionEnum.NO_ERMSSION);
        }

        if (file == null) {
            throw new ZekeException(400, "请上传文件");
        }
        if (!file.getOriginalFilename().contains(".xlsx") && !file.getOriginalFilename().contains(".xls")) {
            throw new ZekeException(400, "只支持xlsx和xls文件格式");
        }
        List<MechanRankAddBatchReq> list;
        try {
            list = ExtUtils.importExcel(file, 1, 1, MechanRankAddBatchReq.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ZekeException(400, e.getMessage());
        }
        if (list == null || list.isEmpty()) {
            throw new ZekeException(400, "文档数据为空");
        }
        // 校验手机号是否注册
        QueryWrapper<MechanUser> q = new QueryWrapper<>();
        q.lambda().in(MechanUser::getPhone, list.stream().map(MechanRankAddBatchReq::getAdminPhone).collect(Collectors.toList()));
        q.lambda().ne(MechanUser::getStatus, MechanConstants.MechanUserStatus.DEL);
        q.lambda().select(MechanUser::getPhone);
        List<MechanUser> exists = mechanUserService.list(q);
        if (exists != null && !exists.isEmpty()) {
            throw new ZekeException(400, "管理员手机号已存在:" + StringUtils.join(exists.stream().map(MechanUser::getPhone).collect(Collectors.toList()), ","));
        }
        // 校验机构名是否注册
        QueryWrapper<MechanRank> qq = new QueryWrapper<>();
        qq.lambda().in(MechanRank::getName, list.stream().map(MechanRankAddBatchReq::getName).collect(Collectors.toList()));
        qq.lambda().ne(MechanRank::getStatus, MechanConstants.MechanStatus.DEL);
        qq.lambda().select(MechanRank::getName);
        List<MechanRank> existsName = list(qq);
        if (existsName != null && !existsName.isEmpty()) {
            throw new ZekeException(400, "机构名字已存在:" + StringUtils.join(existsName.stream().map(MechanRank::getName).collect(Collectors.toList()), ","));
        }
        for (MechanRankAddBatchReq rank : list) {
            //对象属性都为null 则过滤 excel转入obj已有判断, 这里就不需要
//            if (ObjectUtils.objCheckIsNull(rank)) {
//                continue;
//            }
            //字段校验
            String verifyStr = ValidatorUtils.verifyStr(rank, MechanRankAddBatchReq.class);
            if (!StringUtils.isBlank(verifyStr)) {
                continue;
            }
            MechanRank mechanRank = new MechanRank();
            BeanUtils.copyProperties(rank, mechanRank);
            mechanRank.setTapId(tapId);
            mechanRank.setStatus(MechanConstants.MechanStatus.NORMAL);

            mechanRank.setCreateDate(LocalDateTime.now());
            mechanRank.setUpdateDate(LocalDateTime.now());
            mechanRank.setCreateId(loginInfo.getId());
            mechanRank.setCreateName(loginInfo.getName());
            mechanRank.setGlobalId(UUID.randomUUID().toString());
            int i = getBaseMapper().insert(mechanRank);
            if (i <= 0) {
                throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
            }
            int id = mechanRank.getId();
            //添加管理员
            MechanUser mechanUser = new MechanUser();
            mechanUser.setAccount(rank.getAdminPhone());
            mechanUser.setPhone(rank.getAdminPhone());
            mechanUser.setName(rank.getAdminName());
            mechanUser.setCreateName(loginInfo.getName());
            mechanUser.setCreateDate(LocalDateTime.now());
            String salt = CodecUtils.generateSalt();
            mechanUser.setSalt(salt);
            mechanUser.setPassword(CodecUtils.md5Hex(mechanUser.getPhone().substring(mechanUser.getPhone().length() - 6), mechanUser.getSalt()));
            mechanUser.setMechanId(id);
            mechanUser.setType(MechanConstants.MechanUserType.ADMIN);
            mechanUser.setStatus(MechanConstants.MechanUserStatus.NORMAL);
            mechanUser.setCreateId(loginInfo.getId());
            boolean flag = mechanUserService.save(mechanUser);
            if (!flag) {
                throw new ZekeException(400, "添加机构管理员失败");
            }
        }
    }

    /**
     * 修改机构
     *
     * @param req
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMechanRank(MechanRankUpdateReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        if (loginInfo.getType() != LoginInfo.UserType.ADMIN) {
            throw new ZekeException(ZkExceptionEnum.NO_ERMSSION);
        }
        MechanRank mechanRank = getById(req.getId());
        if (mechanRank == null) {
            throw new ZekeException(ZkExceptionEnum.MECHAN_NOT_FOUND);
        }
        if (!mechanRank.getName().equals(req.getName())) {
            //修改了机构名
            QueryWrapper<MechanRank> qq = new QueryWrapper<>();
            qq.lambda().eq(MechanRank::getName, req.getName())
                    .ne(MechanRank::getStatus, MechanConstants.MechanStatus.DEL);
            MechanRank mechanRank2 = getOne(qq);
            if (mechanRank2 != null) {
                throw new ZekeException(400, "机构名字已存在");
            }
        }
        if (!mechanRank.getAdminPhone().equals(req.getAdminPhone())) {
            // 修改机构管理员
            QueryWrapper<MechanUser> qw = new QueryWrapper<>();
            qw.lambda().ne(MechanUser::getStatus, MechanConstants.MechanStatus.DEL)
                    .eq(MechanUser::getPhone, req.getAdminPhone());
            MechanUser mechanUser = mechanUserService.getOne(qw);
            if (mechanUser != null) {
                throw new ZekeException(400, "管理员手机号已使用");
            }
            qw = new QueryWrapper<>();
            qw.lambda().ne(MechanUser::getStatus, MechanConstants.MechanStatus.DEL)
                    .eq(MechanUser::getMechanId, req.getId())
                    .eq(MechanUser::getType, MechanConstants.MechanUserType.ADMIN);
            List<MechanUser> listUser = mechanUserService.list(qw);
            if (listUser != null && !listUser.isEmpty()) {
                mechanUser = listUser.get(0);
                mechanUser.setPhone(req.getAdminPhone());
                mechanUser.setAccount(req.getAdminPhone());
                mechanUserService.updateById(mechanUser);
            }
        }
        BeanUtils.copyProperties(req, mechanRank);
        mechanRank.setUpdateDate(LocalDateTime.now());
        boolean i = updateById(mechanRank);
        if (!i) {
            throw new ZekeException(ZkExceptionEnum.UPDATE_ERROR);
        }
    }

    /**
     * 修改机构状态
     *
     * @param mechanId
     * @param status
     * @param request
     */
    @Override
    public void updateMechanRankStatus(Integer mechanId, Integer status, HttpServletRequest request) {
        MechanRank mechanRank = getById(mechanId);
        if (mechanRank == null) {
            throw new ZekeException(ZkExceptionEnum.MECHAN_NOT_FOUND);
        }
        if (mechanRank.getStatus().equals(status)) {
            return;
        }
        if (!ObjectUtils.refrect(MechanConstants.MechanStatus.class, status)) {
            throw new ZekeException(ZkExceptionEnum.STATUS_DATA_ERROR);
        }
        if (status.equals(MechanConstants.MechanStatus.OFF)) {
            //查询机构下的医生
            LambdaQueryWrapper<DoctorUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.ne(DoctorUser::getStatus, UserConstants.DoctorUserStatus.DEL)
                    .eq(DoctorUser::getMechanId, mechanId);
            int count = doctorUserService.getBaseMapper().selectCount(wrapper);
            if (count > 0) {
                throw new ZekeException("医生数量不为空,请先移交到其他机构再注销");
            }
        }
        mechanRank.setStatus(status);
        boolean i = updateById(mechanRank);
        //删除机构,把机构下的管理员也删掉, 机构下的医生也删掉
        if (status == MechanConstants.MechanStatus.DEL) {
            UpdateWrapper<MechanUser> uw = new UpdateWrapper<>();
            uw.lambda().set(MechanUser::getStatus, MechanConstants.MechanUserStatus.DEL)
                    .eq(MechanUser::getMechanId, mechanId);
            mechanUserService.update(uw);
            QueryWrapper<DoctorUser> qw = new QueryWrapper<>();
            qw.lambda().eq(DoctorUser::getMechanId, mechanId)
                    .ne(DoctorUser::getStatus, UserConstants.DoctorUserStatus.DEL);
            List<DoctorUser> list = doctorUserService.list(qw);
            list.forEach(d -> {
                doctorUserService.updateDoctorUserStatusById(d.getId(), UserConstants.DoctorUserStatus.DEL);
            });
        }
        if (!i) {
            throw new ZekeException(ZkExceptionEnum.UPDATE_ERROR);
        }
        if (status == MechanConstants.MechanStatus.DISABLEADMIN
                || status == MechanConstants.MechanStatus.DEL) {
            redisTemplate.delete(redisTemplate.keys(HealthConstants.ClientType.HEALTHMOB + mechanId + "-*"));
            redisTemplate.delete(redisTemplate.keys(HealthConstants.ClientType.HEALTHPC + mechanId + "-*"));
            redisTemplate.delete(redisTemplate.keys(HealthConstants.ClientType.HEALTHMECHAN + mechanId + "-*"));
        }
    }

    /**
     * 分页查询机构列表
     *
     * @param req
     * @return
     */
    @Override
    public Page<MechanRankPageRes> getMechanRankPage(MechanRankPageReq req) {
        Assert.verifyStatusIdsParam(req.getStatus(), "status", false);
        Assert.verifyStatusIdsParam(req.getTapId(), "tapId", false);
        if (!StringUtils.isBlank(req.getStatus())) {
            req.setStatusStr(req.getStatus().split(","));
        }
        //PageHelper
        Page<MechanRankPageRes> page = req.pagePojo();
        page = getBaseMapper().getMechanPage(page, req);
        return page;
    }

    /**
     * 分页查询机构, 用来选择框的列表
     *
     * @param req
     * @return
     */
    @Override
    public List<MechanRankSelectRes> getMechanRankSelect(MechanRankSelectReq req) {
        return getBaseMapper().getMechanSelect(req);
    }

    /**
     * 审核机构信息
     *
     * @param req
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reviewMechanRankInfo(MechanInfoReviewReq req) {
        if (!ObjectUtils.refrect(MechanConstants.MechanStatus.class, req.getStatus())) {
            throw new ZekeException(ZkExceptionEnum.STATUS_DATA_ERROR);
        }
        MechanRank mechanRank = getById(req.getMechanId());
        if (mechanRank == null) {
            throw new ZekeException(400, "机构不存在");
        }
        if (req.getStatus().equals(MechanConstants.MechanStatus.REVIEW_REJECT)) {
            if (StringUtils.isBlank(req.getMsg())) {
                throw new ZekeException(400, "审核信息不能为空");
            }
        }
        if (req.getStatus().equals(mechanRank.getStatus())) {
            return;
        }
        MechanRankApply mechanRankApply = mechanRankApplyService.reviewMechanRankApply(req);
        if (req.getStatus().equals(MechanConstants.MechanStatus.NORMAL)) {
            BeanUtils.copyProperties(mechanRankApply, mechanRank);
        }
        MechanRank update = new MechanRank();
        update.setId(req.getMechanId());
        update.setStatus(req.getStatus());
        updateById(update);
        mechanReviewLogService.createMechanReviewLog(req);
    }

    /**
     * 查询机构申请审核记录
     *
     * @param req
     * @return
     */
    @Override
    public IPage<MechanRankApplyPageRes> queryMechanRankApplyPage(MechanRankApplyPageReq req) {
        Assert.verifyStatusIdsParam(req.getClass(), req);
        IPage<MechanRankApplyPageRes> iPage = req.pagePojo();
        return getBaseMapper().queryMechanRankApplyPage(iPage, req);
    }

    /**
     * 查询机构审核列表
     *
     * @param req
     * @return
     */
    @Override
    public IPage<MechanRankReviewPageRes> queryMechanRankReviewPage(MechanRankReviewPageReq req) {
        Assert.verifyStatusIdsParam(req.getClass(), req);
        if (StringUtils.isBlank(req.getStatus())) {
            req.setStatus(MechanConstants.MechanStatus.REVIEW_PROCESS);
        }
        IPage<MechanRankReviewPageRes> iPage = req.pagePojo();
        iPage = getBaseMapper().queryMechanRankReviewPage(iPage, req);
        return iPage;
    }

    /**
     * @param idList:
     * @return List<Integer>
     * @description 查询不存在的机构id
     * @author czg
     * @date 2023/4/25 14:04
     */
    @Override
    public List<Integer> queryNotExistsMechanId(List<Integer> idList) {
        if (idList == null || idList.isEmpty()) {
            return idList;
        }
        QueryWrapper<MechanRank> qw = new QueryWrapper<>();
        qw.lambda().ne(MechanRank::getStatus, MechanConstants.MechanStatus.DEL)
                .in(MechanRank::getId, idList)
                .select(MechanRank::getId);
        List<MechanRank> list = list(qw);
        if (list == null || list.isEmpty()) {
            return idList;
        }
        List<Integer> exIds = list.stream().map(MechanRank::getId).collect(Collectors.toList());
        idList.removeAll(exIds);
        return idList;
    }

    @Override
    public List<DoctorDetail> getDoctorList(Integer mechanId) {
        List<DoctorDetail> doctorUserList = baseMapper.getDoctorList(mechanId);
        return doctorUserList;
    }

    @Override
    public void moveDoctorToMechanRank(DoctorToMechanReq doctorToMechanReq) {
        LambdaUpdateWrapper<DoctorUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(DoctorUser::getId, doctorToMechanReq.getDoctorIds())
                .set(DoctorUser::getMechanId, doctorToMechanReq.getMechanId());
        doctorUserService.update(updateWrapper);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertRankApply(MechanRankApplyAddReq mechanRankApplyAddReq) {
        Integer mechanId = null;
        MechanRankApply mechanRankApply = new MechanRankApply();
        BeanUtils.copyProperties(mechanRankApplyAddReq, mechanRankApply);
        if (mechanRankApplyAddReq.getMechanId() == null) {
            QueryWrapper<MechanRank> qw = new QueryWrapper<>();
            qw.lambda().eq(MechanRank::getName, mechanRankApplyAddReq.getName())
                    .ne(MechanRank::getStatus, MechanConstants.MechanStatus.DEL);
            MechanRank mechanRank = getOne(qw);
            if (mechanRank != null) {
                throw new ZekeException(400, "机构名字已存在");
            }
            if (mechanUserService.checkPhoneUsed(mechanRankApplyAddReq.getAdminPhone())) {
                throw new ZekeException(400, "手机号已使用");
            }
            //插入到机构表
            MechanRank newMechanRank = new MechanRank();
            BeanUtils.copyProperties(mechanRankApplyAddReq, newMechanRank);
            //机构待审核
            newMechanRank.setStatus(MechanConstants.MechanStatus.UN_REVIEW);
            int i = getBaseMapper().insert(newMechanRank);
            if (i <= 0) {
                throw new ZekeException("添加失败");
            }
            mechanId = newMechanRank.getId();
            //添加管理员
            MechanUser mechanUser = new MechanUser();
            mechanUser.setAccount(newMechanRank.getAdminPhone());
            mechanUser.setPhone(newMechanRank.getAdminPhone());
            mechanUser.setName(newMechanRank.getAdminName());
            mechanUser.setCreateDate(LocalDateTime.now());
            String salt = CodecUtils.generateSalt();
            mechanUser.setSalt(salt);
            mechanUser.setPassword(CodecUtils.md5Hex(mechanUser.getPhone().substring(mechanUser.getPhone().length() - 6), mechanUser.getSalt()));
            mechanUser.setMechanId(mechanId);
            mechanUser.setType(MechanConstants.MechanUserType.ADMIN);
            //管理员待审核
            mechanUser.setStatus(MechanConstants.MechanUserStatus.WAIT_USE);
            boolean flag = mechanUserService.save(mechanUser);
            if (!flag) {
                throw new ZekeException(400, "添加机构管理员失败");
            }
            //绑定邀请码
            String inviteCode = mechanRankApplyAddReq.getInviteCode();
            if (HealthConstants.InviteCodePrefixConstants.SALE_PREFIX.equals(inviteCode.substring(0, 1))) {
                LambdaQueryWrapper<AdminSaleInfo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(AdminSaleInfo::getInviteCode, mechanRankApplyAddReq.getInviteCode());
                AdminSaleInfo adminSaleInfo = adminSaleInfoService.getOne(wrapper);
                SaleInviteMechan saleInviteMechan = new SaleInviteMechan();
                saleInviteMechan.setMechanId(mechanId)
                        .setCreateDate(LocalDateTime.now())
                        .setSaleId(adminSaleInfo.getAdminId())
                        .setStatus(AdminConstants.UserStatus.NORMAL);
                saleInviteMechanService.save(saleInviteMechan);
            } else if (HealthConstants.InviteCodePrefixConstants.AGENT_PREFIX.equals(inviteCode.substring(0, 1))) {
                LambdaQueryWrapper<Agent> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Agent::getInviteCode, mechanRankApplyAddReq.getInviteCode());
                Agent agent = agentService.getOne(wrapper);
                AgentMechanBind agentInviteMechan = new AgentMechanBind();
                agentInviteMechan.setMechanId(mechanId)
                        .setCreateDate(LocalDateTime.now())
                        .setAgentId(agent.getId())
                        .setStatus(AdminConstants.UserStatus.NORMAL);
                agentMechanBindService.save(agentInviteMechan);
            }
        } else {//机构已经存在
            mechanId = mechanRankApplyAddReq.getMechanId();
            MechanRank mechanRank = this.getById(mechanId);
            if (mechanRank == null) {
                throw new ZekeException(400,"机构不存在");
            }
            if (mechanRank.getStatus().equals(MechanConstants.MechanStatus.UN_REVIEW)
                    || mechanRank.getStatus().equals(MechanConstants.MechanStatus.NORMAL)) {
                throw new ZekeException(400,"请勿重复提交注册申请信息");
            }
            BeanUtils.copyProperties(mechanRankApplyAddReq, mechanRank);
            mechanRank.setStatus(MechanConstants.MechanStatus.UN_REVIEW);
            this.updateById(mechanRank);
        }
        //插入一条申请记录
        mechanRankApply.setCreateDate(LocalDateTime.now())
                .setUpdateDate(LocalDateTime.now())
                .setMechanId(mechanId)
                .setStatus(MechanConstants.MechanStatus.UN_REVIEW);
        mechanRankApplyService.save(mechanRankApply);
    }

    @Override
    public IPage<MechanRankPageRes> removeMechanRankPage(MechanRankPageReq req) {
        IPage<MechanRankPageRes> iPage = req.pagePojo();
        iPage = getBaseMapper().removeMechanRankPage(iPage, req);
        return iPage;
    }

    /**
     * 获取机构的名字
     *
     * @param mechanId
     * @return
     */
    @Override
    public String queryMechanName(Integer mechanId) {
        QueryWrapper<MechanRank> qw = new QueryWrapper<>();
        qw.lambda().eq(MechanRank::getId, mechanId);
        qw.lambda().select(MechanRank::getName);
        MechanRank mechanRank = getOne(qw);
        return mechanRank == null ? "未知机构" : mechanRank.getName();
    }
}
